from app import lxq
from app.models import db
from app.models.project_role import ProjectRole
from app.utils.logger import Log
from app.models.project import Project
from datetime import datetime

class ProjectRoleDao(object):
    log = Log("ProjectRoleDao")

    @staticmethod
    def list_project_by_user(user_id):
        '''
        通过user_id 获取对应权限可展示的项目列表id
        :param user_id:
        :return:
        '''
        try:
            projects = ProjectRole.query.filter_by(user_id=user_id, deleted_at=None).all()
            return [p.id for p in projects], None
        except Exception as e:
            ProjectRoleDao.log.error(f"查询用户: {user_id} 项目失败, {e}")
            return [],f"查询项目失败，{e}"

    @staticmethod
    def add_project_role(user_id, project_id, project_role, create_user, user_role):
        '''
        为项目添加成员
        :param user_id: 用户id
        :param project_id: 项目id
        :param project_role: 用户角色
        :param user: 创建人
        :param user_role: 创建人角色
        :return:
        '''
        try:
            # 先判断用户是否在项目中(同一个user_id只能匹配一个角色)
            role = ProjectRole.query.filter_by(user_id=user_id, project_id=project_id,
                                               deleted_at=None).first()
            if role:
                # 说明角色存在
                return "该用户已存在"
            # 判断是否有权限添加
            err = ProjectRoleDao.has_permission(project_id,project_role,create_user,user_role)
            if not err:
                role = ProjectRole(user_id,project_id,project_role,create_user)
                db.session.add(role)
                db.session.commit()
        except Exception as e:
            ProjectRoleDao.log.error(f"添加项目用户失败， {e}")
            return f"添加项目用户失败， {e}"
        return None



## 列出角色
    @staticmethod
    def list_role(project_id: int):
        '''
        通过project_id去获取这个项目的所有角色列表。
        :param project_id:
        :return:
        '''
        try:
            roles = ProjectRole.query.filter_by(project_id=project_id, deleted_at=None).all()
            return roles, None
        except Exception as e:
            ProjectRoleDao.log.error(f"查询项目：{project_id} 角色列表失败， {e}")
            return [], f"查询项目：：{project_id} 角色列表失败， {e}"

    # 编辑角色
    @staticmethod
    def update_project_role(role_id, project_role, user, user_role):
        '''
        判断他要修改的角色id是否存在
        判断是否是超管或者owner
        判断要修改的是不是组长
        判断他自身是否是组长
        :param role_id: 成员角色 id
        :param project_role: 项目角色
        :param user: 用户id
        :param user_role: 用户的角色id
        :return:
        '''
        try:
            role = ProjectRole.query.filter_by(id=role_id, deleted_at=None).first()
            if role is None:
                return "该户用成员不存在"
            if user_role != lxq.config.get("ADMIN"):
                project = Project.query.filter_by(id=role.project_id).first()
                if project is None:
                    return "该项目不存在"

                if project.owner != user and role.project_role == 1:
                    # 既不是owner也不是超管，无法修改阻止的权限
                    return "不能修改其他组长的权限"

                updater_role = ProjectRole.query.filter_by(user_id=user, project_id=role.project_id, deleted_at=None).first()
                # 如果 不是这个项目的成员  或者
                if updater_role is None or updater_role.project_role == 1:
                    return "对不起，你没有权限"

            role.project_role = project_role
            role.updated_at = datetime.now()
            role.update_user = user
            db.session.commit()
        except Exception as e:
            ProjectRoleDao.log.error(f"修改项目用户失败, {e}")
            return f"修改项目用户失败, {e}"
        return None


    @staticmethod
    def has_permission(project_id, project_role, user, user_role, project_admin=False):
        '''

        :param project_id:
        :param project_role:
        :param user_role:
        :param project_admin:
        :return:
        '''
        if user_role != lxq.config.get("ADMIN"):
            # 当用户的角色不是admin
            project = Project.query.filter_by(id=project_id).first()
            if project is None:
                return "该项目不存在"
            # 当项目的拥有者不是当前用户
            if project.owner != user:
                # 当前用户不是组长 并且 也不是 项目管理员
                if project_admin and project_role == 1:
                    return "不能修改组长权限"

                update_role = ProjectRole.query.filter_by(user_id=user, project_id=project_id,deleted_at=None).first()
                if update_role is None or update_role.project_role == 0:
                    return "对不起，你没有权限"
        return None



    @staticmethod
    def delete_project_role(role_id, user, user_role):
        try:
            role = ProjectRole.query.filter_by(id=role_id, deleted_at=None).first()
            if role is None:
                return "用户角色不存在"


        except Exception as e:
            ProjectRoleDao.log.error(f"删除项目用户失败, {e}")
            return f"删除项目用户失败，{e}"


